package com.eunion.boot.security;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import com.eunion.boot.spring.LocaleMessageSourceService;
import com.eunion.boot.spring.SpringUtil;

/**
 * 自定义403无权限页面.
 * 
 * @since 2017年1月1日
 */
@Component
public class SysAccessDeniedHandler implements AccessDeniedHandler {

	//	private static final String DEF_ERROR_PAGE_PATH = "admin/403";

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)
	    throws IOException, ServletException {
		boolean isAjax = isAjaxRequest(request);
		logger.debug("是否是ajax请求：{}", isAjax);
		if (!isAjax) {
			request.setAttribute("isAjaxRequest", isAjax);
			request.setAttribute("message", accessDeniedException.getMessage());
			RequestDispatcher dispatcher = request.getRequestDispatcher("/admin/403auth.jsp");
			//response.sendRedirect(request.getContextPath()+"/authNotPass.jsp");
			dispatcher.forward(request, response);
		} else {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/plain");

			LocaleMessageSourceService localeMessageSourceService = SpringUtil.getBean(LocaleMessageSourceService.class);
			String varifyMsg = localeMessageSourceService.getMessage(request, "sys.login.403Forbidden");//权限不足
			response.getWriter().write(varifyMsg);
			response.getWriter().close();
		}
	}
	
	private boolean isAjaxRequest(HttpServletRequest request) {
		String header = request.getHeader("X-Requested-With");
		if (header != null && "XMLHttpRequest".equalsIgnoreCase(header))
			return true;
		else
			return false;
	}
}
